package com.example.projectmanagement.service;

import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.model.UserRole;
import com.example.projectmanagement.repository.UserRepository;
import com.example.projectmanagement.repository.RoleRepository;
import com.example.projectmanagement.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserRoleService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private UserRoleRepository userRoleRepository;
    
    /**
     * 为用户分配角色
     */
    public void assignRoleToUser(Long userId, Long roleId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        // 检查是否已存在关联
        if (userRoleRepository.findByUserAndRole(user, role).isPresent()) {
            throw new RuntimeException("用户已拥有该角色");
        }
        
        UserRole userRole = new UserRole();
        userRole.setUser(user);
        userRole.setRole(role);
        userRoleRepository.save(userRole);
    }
    
    /**
     * 获取用户的所有角色
     */
    public List<Role> getRolesByUserId(Long userId) {
        return userRoleRepository.findRolesByUserId(userId);
    }
    
    /**
     * 移除用户的角色
     */
    public void removeRoleFromUser(Long userId, Long roleId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        Optional<UserRole> userRoleOpt = userRoleRepository.findByUserAndRole(user, role);
        if (userRoleOpt.isPresent()) {
            userRoleRepository.delete(userRoleOpt.get());
        } else {
            throw new RuntimeException("用户未拥有该角色");
        }
    }
}